package com.my.toolkit;

import java.text.SimpleDateFormat;

import org.springframework.stereotype.Component;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

public class JsonUtil {
	public static final JsonUtil NON_NULL=new JsonUtil();
	public static final JsonUtil NULL=new JsonUtil(false);
	
	private ObjectMapper objectMapper;
	
	public JsonUtil(boolean notNull) {
		objectMapper = new ObjectMapper();
		// 不显示为null的字段
		if(notNull) {
			objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		}
		SimpleModule simpleModule = new SimpleModule();
		simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
		objectMapper.registerModule(simpleModule);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}

	public JsonUtil() {
		this(true);
	}

	public String toString(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	public <T> T toBean(String str, Class<T> t) {
		try {
			return objectMapper.readValue(str, t);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	public String toFormatString(Object obj) {
		try {
			return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		
	}

	public ObjectMapper getObjectMapper() {
		return objectMapper;
	}
	
	
}
